<?php

namespace app\controllers;

use app\lib\BaseFunction;
use app\models\Favor;
use app\models\Invoice_new;
use app\models\Product;
use app\models\Purchase;
use app\models\QuoteProduct;
use app\models\Staff;
use app\service\ContainerProductService;
use app\service\SellService;
use yii;
use yii\data\Pagination;

class PurchaseController extends CommonController
{
    public $layout = false;

    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * 采购合同列表
     */
    public function actionPurchase()
    {
        $p                            = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s                            = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 15;
        $where                        = [];
        $where['invoice']             = trim(yii::$app->request->get('invoice'));
        $where['purchase_num']        = trim(yii::$app->request->get('purchase_num'));
        $where['job_number']          = trim(yii::$app->request->get('job_number'));
        $where['product_status']      = yii::$app->request->get('product_status');
        $where['product_status_time'] = yii::$app->request->get('product_status_time');
        $where['s_num']               = yii::$app->request->get('s_num');
        $where['pay_status']          = yii::$app->request->get('pay_status');
        $where['last_modify']         = yii::$app->request->get('last_modify');
        if ($this->user['role'] != 1 && $this->user['role'] != 2) {
            if (BaseFunction::checkJieke($this->user['role'])) {
                if ($this->user['role'] == 9) {
                    $where['job_number'] = $this->user['job_number'];
                } else {
                    if (empty($where['job_number'])) {
                        $model               = new Staff();
                        $job_number          = $model->getStaffByGroup(4);
                        $where['job_number'] = $job_number;
                    }
                }
            } else {
                $where['job_number'] = $this->user['job_number'];
            }
        }
        $sellService = new SellService();
        $data        = $sellService->purchaseList($p, $s, $where);
        $list        = $data['list'];
        foreach ($list as $k => $v) {
            $list[$k]['purchase_list']    = json_decode($v['product_list'], true);
            $list[$k]['have_pay']         = 0;
            $list[$k]['not_pay']          = $v['total_fee'];
            $list[$k]['last_modify_time'] = '';
            if (isset($data['purchase'][$v['purchase_num']])) {
                $tmp                       = $data['purchase'][$v['purchase_num']];
                $list[$k]['have_pay']      = $tmp['money'];
                $list[$k]['not_pay']       = $v['total_fee'] - $tmp['money'];
                $list[$k]['last_pay_time'] = $tmp['last_modify'];
            }

        }
        $size = $data['size'];
        return \json_encode(['purchase' => $data['purchase'], 'list' => $list, 'size' => $size]);

    }

    /**
     *采购合同详情
     */
    public function actionInfo()
    {
        $number = yii::$app->request->get('number', '');
        if (!$number) {
            return json_encode(['code' => 0, 'msg' => '数据错误']);
        }
        $model = new Purchase();
        $info  = $model->one(['purchase_num' => $number]);
        return json_encode(['code' => 1, 'msg' => $info]);

    }

    public function actionProduct_list()
    {
        $where                 = [];
        $page                  = yii::$app->request->get('page') ? yii::$app->request->get('page') : 1;
        $pageSize              = yii::$app->request->get('per-page') ? yii::$app->request->get('per-page') : 100;
        $where['product_name'] = trim(yii::$app->request->get('product'));
        $where['date']         = yii::$app->request->get('date');
        $where['enddate']      = yii::$app->request->get('enddate');
        $where['job_number']   = trim(yii::$app->request->get('job_number'));
        $model                 = new QuoteProduct();
        $order                 = ['date' => SORT_DESC];
        $list                  = $model->all($where, ($page - 1) * $pageSize, $pageSize, $order);
        $productArr            = [];
        $resList               = [];
        foreach ($list as $v) {
            $productArr[]          = $v['id'];
            $resList[$v['date']][] = $v;
        }
        $favorModel  = new Favor();
        $favorList   = $favorModel->all(['product_id' => $productArr, 'user_id' => $this->user['id']]);
        $size        = $model->size($where);
        $page        = new Pagination(['totalCount' => $size, 'pageSize' => $pageSize]);
        $staff_model = new Staff();
        $staff_list  = $staff_model->get_all_saleman();
        return $this->render('product_list', ['staff' => $staff_list, 'favorList' => $favorList, 'list' => $resList, 'page' => $page]);
    }

    public function actionList()
    {

        $where                 = [];
        $page                  = yii::$app->request->get('page') ? yii::$app->request->get('page') : 1;
        $pageSize              = yii::$app->request->get('per-page') ? yii::$app->request->get('per-page') : 100;
        $where['product_name'] = trim(yii::$app->request->get('product'));
        $where['date']         = yii::$app->request->get('date');
        $where['enddate']      = yii::$app->request->get('enddate');
        $where['job_number']   = trim(yii::$app->request->get('job_number'));
        $model                 = new QuoteProduct();
        $order                 = ['date' => SORT_DESC];
        $list                  = $model->all($where, ($page - 1) * $pageSize, $pageSize, $order);
        $productArr            = [];
        $resList               = [];
        foreach ($list as $v) {
            $productArr[]          = $v['id'];
            $resList[$v['date']][] = $v;
        }
        $favorModel  = new Favor();
        $favorList   = $favorModel->all(['product_id' => $productArr, 'user_id' => $this->user['id']]);
        $size        = $model->size($where);
        $page        = new Pagination(['totalCount' => $size, 'pageSize' => $pageSize]);
        $staff_model = new Staff();
        $staff_list  = $staff_model->get_all_saleman();
        return \json_encode(['staff' => $staff_list, 'favorList' => $favorList, 'list' => $resList, 'page' => $page]);
    }

    /**
     * 删除收藏商品
     */
    public function actionDelFavor()
    {
        if (yii::$app->request->isPost) {
            $id    = yii::$app->request->post('id'); //采购编号
            $model = new Favor();
            $model->delete(['product_id' => $id, 'user_id' => $this->user['id']]);
        }
    }

    /**添加收藏
     * @return string
     */
    public function actionAddFavor()
    {
        if (yii::$app->request->isPost) {
            $id      = yii::$app->request->post('id');
            $user_id = $this->user['id'];
            $model   = new Favor();
            if ($model->insert(['product_id' => $id, 'user_id' => $user_id])) {
                return json_encode(['code' => 1, 'msg' => 'Collection success']);
            } else {
                return json_encode(['code' => 0, 'msg' => 'Collection fail']);
            }
        }
    }

    public function actionFavorList()
    {
        $page     = yii::$app->request->get('page') ? yii::$app->request->get('page') : 1;
        $pageSize = yii::$app->request->get('per-page') ? yii::$app->request->get('per-page') : 15;
        $arr      = [];
        $model    = new Favor();
        $list     = $model->all(['user_id' => $this->user['id']], ($page - 1) * $pageSize, $pageSize);
        foreach ($list as $v) {
            $arr[] = $v['product_id'];
        }
        if (!empty($arr)) {
            $model = new QuoteProduct();
            $list2 = $model->all(['id' => $arr]);
            foreach ($list2 as $k => $v) {
                foreach ($list as $v2) {
                    if ($v2['product_id'] == $v['id']) {
                        $list2[$k]['remark'] = $v2['remark'];
                        $list2[$k]['url']    = $v2['url'];
                        break;
                    }
                }
            }
        } else {
            $list2 = [];
        }
        return $this->render('favorList', ['list' => $list2]);
    }

    /**
     * 更新产品收藏信息
     */
    public function actionUpdateFavor()
    {
        if (yii::$app->request->isPost) {
            $id    = yii::$app->request->post('id');
            $param = yii::$app->request->post('param');
            $value = yii::$app->request->post('value');
            $model = new Favor();
            if ($model->save([$param => $value, 'user_id' => $this->user['id']], ['product_id' => $id])) {
                echo json_encode(['code' => 1, 'msg' => 'update success']);
            } else {
                echo json_encode(['code' => 0, 'msg' => 'update failed']);
            }
        }
    }

    /**
     * 添加采购合同
     */
    public function actionPurchaseAdd()
    {
        $data              = yii::$app->request->post();
        $model             = new Purchase();
        $data['create_at'] = date('Y-m-d');
        //添加insert
        $data['job_number']    = $this->user['job_number'];
        $data['qianding_date'] = date('Y-m-d');
        //生成一个采购编号
        $data['purchase_num'] = $model->generate_purchase_num();
        $re                   = $model->insert_purchase($data);
        if ($re) {
            //如果是捷克采购合同产品加入排柜表
            if (BaseFunction::checkJieke($this->user['role'])) {
                $insertId = yii::$app->db->getLastInsertID();
                //添加装箱
                ContainerProductService::addContainerProduct($data, $insertId);
            }
            return \json_encode(['code' => 1, 'msg' => '添加成功']);
        } else {
            return \json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
        }
    }

    /**采购合同信息
     * @return string
     */
    public function actionPurchaseInfo()
    {
        $id    = yii::$app->request->get('id');
        $model = new Purchase();
        $info  = $model->get_purchase_by_id($id);
        return \json_encode(['data' => $info]);
    }

    /**
     *采购合同更新
     */
    public function actionPurchaseUpdate()
    {
        $data = yii::$app->request->post();
        $id   = $data['id'];
        if (!isset($id) || !is_numeric($id)) {
            return \json_encode(['code' => 0, 'msg' => '参数错误']);
        }
        $model = new Purchase();
        $info  = $model->get_purchase_by_id($id);
        //订单是否完结
        if (isset($info['invoice'])) {
            $invoice = new Invoice_new();
            $info    = $invoice->one(['invoice' => $info['invoice']]);
            if ($info) {
                if ($info['is_jiesuan'] == 3) {
                    return \json_encode(['code' => 0, 'msg' => '订单已结算，无法继续修改']);
                }
            }
        }
        //捷克部门装箱信息需要更新
        unset($data['id']);
        $re   = $model->updateByParam($data, $id);
        $info = $model->one(['id' => $id]);
        //采购装箱先删除在重新添加
        ContainerProductService::delContainerProduct($info['purchase_num']);
        ContainerProductService::addContainerProduct($info, $id);
        if ($re) {
            return \json_encode(['code' => 1, 'msg' => '修改成功']);
        } else {
            return \json_encode(['code' => 0, 'msg' => '修改失败,请重试']);
        }
    }

    /*
    业务员采购产品
     */
    public function actionProduct()
    {
        $p     = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s     = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 1;
        $where = [];
        if ($this->user['role'] == 1) {
            //管理员查看全部
        } elseif ($this->user['role'] == 3) {
            $model            = new Invoice_new();
            $where['invoice'] = $model->get_invoice_by_job_number($this->user['job_number']);

            //业务员查看自己
        } elseif ($this->user['role'] == 4) {
            //采购查看有关业务员的
            $model            = new Staff();
            $info             = $model->get_all_saleman($this->user['job_number']);
            $where['invoice'] = json_decode($info['saleman_list'], true);
        }
        $product_model = new Product();
        $list          = $product_model->get_product_list($p, $s, $where);
        $product_model->get_product_size($where);
        yii::$app->view->params['list'] = $list;
        return $this->render('product');
    }

    public function actionPurchase_update()
    {
        if (yii::$app->request->isPost) {
            $id     = yii::$app->request->post('id');
            $column = yii::$app->request->post('column');
            $value  = yii::$app->request->post('value');
            $table  = yii::$app->db->tablePrefix . 'product';
            $sql    = 'SELECT is_jiesuan from jingsourcing_invoice_new a
                    LEFT JOIN jingsourcing_product as b ON a.invoice=b.invoice
                    WHERE b.id = :id';
            $re = yii::$app->db->createCommand($sql, ['id' => $id])->queryOne();
            if ($re) {
                if ((int) $re['is_jiesuan'] == 3) {
                    return json_encode(['code' => 0, 'msg' => '订单已结算']);
                }
            }
            $re = yii::$app->db->createCommand()->update($table, [$column => $value], ['id' => $id])->execute();
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '更新成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '更新失败，请重试']);
            }
        }
    }

    //添加商品
    public function actionAdd_product()
    {
        if (yii::$app->request->isPost) {
            $data['invoice']            = yii::$app->request->post('invoice');
            $data['price_rmb']          = yii::$app->request->post('price_rmb');
            $data['number']             = yii::$app->request->post('number');
            $data['customer_extra_fee'] = yii::$app->request->post('customer_extra_fee');
            $data['product_name']       = yii::$app->request->post('product_name');
            $data['price_dollar']       = yii::$app->request->post('price_dollar');
            $data['product_name_en']    = yii::$app->request->post('product_name_en');
            $data['extra_fee']          = yii::$app->request->post('extra_fee');
            $table                      = yii::$app->db->tablePrefix . 'product';
            $model                      = new Invoice_new();
            $info                       = $model->getDetailByInvoice($data['invoice']);
            if ($info['is_jiesuan'] == 3) {
                return json_encode(['code' => 0, 'msg' => '订单已完结，无法继续添加']);
            }
            try {
                $re = yii::$app->db->createCommand()->insert($table, $data)->execute();
                if ($re) {
                    return json_encode(['code' => 1, 'msg' => '添加成功']);
                } else {
                    return json_encode(['code' => 0, 'msg' => '添加失败，请重试']);
                }

            } catch (\Exception $e) {
                return \json_encode(['code' => 0, 'msg' => $e->getMessage()]);
            }

        }
    }
}
